package com.clei.utils;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import com.aspose.cells.WorksheetCollection;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * Excel -> Pdf util
 *
 * @author Y
 * @date 2024-07-30
 */
public class Excel2PdfUtil {

    static {
        // 初始化操作
        setLicense();
    }

    /**
     * word -> pdf
     *
     * @param excelFile excel路径
     * @param pdfFile   pdf路径
     * @return success true/false
     */
    public static boolean toPdf(String excelFile, String pdfFile) {
        // 默认第一个sheet
        return toPdf(excelFile, pdfFile, new int[]{0});
    }

    /**
     * word -> pdf
     *
     * @param excelFile     excel路径
     * @param pdfFile       pdf路径
     * @param convertSheets 转换sheet
     * @return success true/false
     */
    public static boolean toPdf(String excelFile, String pdfFile, int[] convertSheets) {
        boolean success = false;
        try (FileInputStream fis = new FileInputStream(excelFile);
             FileOutputStream fos = new FileOutputStream(pdfFile)) {
            success = toPdf(fis, fos, convertSheets);
        } catch (Exception e) {
            PrintUtil.log("toPdf error excelFile : {}, pdfFile : {}", excelFile, pdfFile, e);
        }
        return success;
    }

    /**
     * excel -> pdf
     *
     * @param inputStream  excel输入流
     * @param outputStream pdf输出流
     * @return success true/false
     */
    public static boolean toPdf(InputStream inputStream, OutputStream outputStream) {
        // 默认第一个sheet
        return toPdf(inputStream, outputStream, new int[]{0});
    }

    /**
     * excel -> pdf
     *
     * @param inputStream   excel输入流
     * @param outputStream  pdf输出流
     * @param convertSheets 转换sheet
     * @return success true/false
     */
    public static boolean toPdf(InputStream inputStream, OutputStream outputStream, int[] convertSheets) {
        boolean success = false;
        try (InputStream is = inputStream;
             OutputStream os = outputStream) {
            Workbook workbook = new Workbook(is);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            // 转换sheet
            setVisible(workbook, convertSheets);
            workbook.save(os, pdfSaveOptions);
            os.flush();
            success = true;
        } catch (Exception e) {
            PrintUtil.log("toPdf error", e);
        }
        return success;
    }

    /**
     * 隐藏workbook中不需要的sheet页
     *
     * @param sheets 显示页的sheet数组
     */
    private static void setVisible(Workbook wb, int[] sheets) {
        if (null == sheets) {
            return;
        }
        Set<Integer> set = IntStream.of(sheets).boxed().collect(Collectors.toSet());
        WorksheetCollection worksheets = wb.getWorksheets();
        int i = 0;
        for (Object worksheet : worksheets) {
            Integer index = i;
            // 未在集合内的设置不可见
            if (!set.contains(index)) {
                Worksheet ws = (Worksheet) worksheet;
                ws.setVisible(false);
            }
            i++;
        }
    }

    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        String licenseStr = "<License>" +
                "<Data>" +
                "<Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products>" +
                "<EditionType>Enterprise</EditionType>" +
                "<SubscriptionExpiry>20991231</SubscriptionExpiry>" +
                "<LicenseExpiry>20991231</LicenseExpiry>" +
                "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" +
                "</Data>" +
                "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>" +
                "</License>";

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(licenseStr.getBytes());
        License license = new License();
        license.setLicense(byteArrayInputStream);
    }
}
